package com.example.controller;

import com.example.impl.OrderServiceImpl;
import com.example.model.WxbCustomer;
import com.example.model.WxbMemeber;
import com.example.model.WxbOrder;
import com.example.model.vo.Result;
import com.example.utils.MatrixToImageWriter;
import com.github.wxpay.sdk.MyWxConfig;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import io.goeasy.GoEasy;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController{

    @Autowired
    private OrderServiceImpl orderService;

    @RequestMapping("/add")
    @ResponseBody
    public Result addOrder(@RequestBody WxbOrder order,HttpServletRequest request){

        Result result =null;
        try {
            orderService.insertOrder(order);

            result =new Result(true,"操作成功");
            try {
                WXPay wxPay = new WXPay(new MyWxConfig());
                Map<String, String> data = new HashMap<String, String>();
                data.put("body", order.getGoodId());
                //订单号
                data.put("out_trade_no", order.getOrderId());
                //设备信息
                data.put("device_info", "PC");
                //支付方式,cny人民币
                data.put("fee_type", "CNY");
                //支付笔数
                data.put("total_fee", "1");
                //请求下单的ip
                data.put("spbill_create_ip", "123.12.12.123");
                //支付成功之后的回调接口
                data.put("notify_url", "http://2cfwsq.natappfree.cc/order/result");
                // 此处指定为扫码支付
                data.put("trade_type", "NATIVE");
                data.put("product_id", "12");

                Map<String, String> resp = wxPay.unifiedOrder(data);

                String codeUrl = resp.get("code_url");
                System.out.println(codeUrl);
                request.getSession().setAttribute("codeUrl",codeUrl);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
            result =   new Result(false,"操作失败");
        }
        return result;
    }

    @RequestMapping("/qrcode")
    public void qrcode(HttpServletRequest request,HttpServletResponse response){

        String codeUrl = (String)request.getSession().getAttribute("codeUrl");
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 200, 200, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", response.getOutputStream());
            System.out.println("创建二维码完成");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @RequestMapping("/result")
    public void gerResult(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String  str = "";
        byte[] buff = new byte[1024];
        int len = 0;
        InputStream inputStream = request.getInputStream();
        while ((len=inputStream.read(buff))!=-1){
           str += new String(buff,0,len);
        }
        System.out.println(str);
        Map<String,String>map = WXPayUtil.xmlToMap(str);
        PrintWriter out = response.getWriter();
        out.print("<xml>" +
                "\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>");
        out.flush();
        out.close();

        String orderId = map.get("out_trade_no");
        GoEasy goEasy = new GoEasy("http://rest-hangzhou.goeasy.io", "BC-dc00f8732b2d48d0b6da872a2c176948");
        goEasy.publish("qf123456","pay-success");

        orderService.updateAlipayState(orderId);


    }


    @RequestMapping("/findByAll")
    public String findAll(Model model){
      WxbMemeber wxbMemeber = (WxbMemeber) SecurityUtils.getSubject().getPrincipal();
        List<WxbOrder> orders= orderService.findByAll(wxbMemeber.getMemeberId());

        model.addAttribute("orders",orders);

        return "generalize";
    }



    @RequestMapping("/findById")
    public String findById(Long oid,Model model){
        WxbOrder order = orderService.findById(oid);
        model.addAttribute("order",order);
        return "desc";
    }

    @RequestMapping("/delectById")
    @ResponseBody
    public Result delectById(Long oid){
        WxbOrder order = orderService.findAndId(oid);
       if (order.getAlipayState().equals("0")){
            orderService.delect(oid);
            return new Result(true,"操作成功");
        }else{
            return new Result(false,"已付款,操作无效");
        }
    }

}

